package com.lancoo.answer.widget.combinationView;

import android.content.Context;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.ivan.GlideEngine;
import com.ivan.easyphotos.EasyPhotos;
import com.lancoo.answer.R;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.CompositionComment;
import com.lancoo.answer.model.bean.DetailComment;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.ItemAsk;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.eventBean.CommentDetailEventBean;
import com.lancoo.answer.model.eventBean.CommentsNoteEventBean;
import com.lancoo.answer.model.eventBean.GreateAnsEvent;
import com.lancoo.answer.model.eventBean.VideoEventBean;
import com.lancoo.answer.util.DpUtils;
import com.lancoo.answer.util.ExamFontSizeAdjustUtils;
import com.lancoo.answer.util.RichTextUtils;
import com.lancoo.answer.util.paperUtils.ChildRightOrWrongJudgeUtils;
import com.lancoo.answer.util.paperUtils.DecimalFormatUtils;
import com.lancoo.answer.view.activity.CompositionCommentActivity;
import com.lancoo.answer.view.fragment.composition.adapter.ImageAdapter;
import com.lancoo.answer.widget.PcDialog;
import com.lancoo.answer.widget.VideoPlayView;
import com.lancoo.answer.widget.span.CenteredImageSpan;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/15 13:42
 * Description:读后续写分段作答adapter
 */
public class CompositionAnswerResultView extends RelativeLayout implements View.OnClickListener {

    private static final String TAG = "CompositionAnswerResult";
    private ChildAudioView childAudioView;
    private String queseID;
    private Child child;
    private Ques ques;
    private Item item;
    private TextView tv_score;
    private CompositionAnswerResultSubView compositionAnswerResultSubView;
    private long clickTime;

    public CompositionAnswerResultView(Context context) {
        super(context);
        init(context);
    }

    public CompositionAnswerResultView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CompositionAnswerResultView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.ev_layout_composition_answer_result, this);
        TextView tv_title = findViewById(R.id.tv_score_des);
        TextView tv_title1 = findViewById(R.id.tv_answer_des);
        TextView tv_title2 = findViewById(R.id.tv_my_answer_des);
        TextView tv_title3 = findViewById(R.id.tv_my_score);
        TextView tv_title4 = findViewById(R.id.tv_comment_des);
        String str = "【";
        float v = tv_title.getPaint().measureText(str);
        tv_title.setTranslationX(-v / 2);
        tv_title1.setTranslationX(-v / 2);
        tv_title2.setTranslationX(-v / 2);
        tv_title3.setTranslationX(-v / 2);
        tv_title4.setTranslationX(-v / 2);
        adjustFontSize();

    }

    public void setQueseID(String queseID) {
        this.queseID = queseID;
    }

    public void setWriteResult(Child child, Ques ques) {
        this.child = child;
        this.ques = ques;
        String genreID = ques.getGenreID();
        if (child.getItemList() == null) {
            return;
        }
        this.item = child.getItemList().get(Math.min(child.getItemList().size() - 1, child.getSelectedItemIndex()));
        showComment();
        StringBuffer analysis = new StringBuffer();
        StringBuffer answer = new StringBuffer();
        for (Item item : child.getItemList()) {
            if (!TextUtils.isEmpty(analysis) && !TextUtils.isEmpty(item.getItemAnalysis())) {
                analysis.append("<br>");
            }
            analysis.append(item.getItemAnalysis());
            if (!TextUtils.isEmpty(answer) && !TextUtils.isEmpty(item.getItemAnswer())) {
                answer.append("<br>");
            }
            answer.append(item.getItemAnswer());
        }

        AnswerAnalysisView answerAnalysisView = findViewById(R.id.answer_analysis_view);
        answerAnalysisView.setAnalysis(analysis.toString());
        answerAnalysisView.setAlignmentType(1);
        TextView tv_answer = findViewById(R.id.tv_answer);
        String childAnswer = answer.toString().replace("$/", "或<br>");

        if (TextUtils.isEmpty(childAnswer)) {
            tv_answer.setText(R.string.ev_item_null);
        } else {
            boolean isNeedTr = TextUtils.equals("52", genreID) || TextUtils.equals("34", genreID);
            boolean isIndentChildAnswer = child.getIsIndentChildAnswer();
            tv_answer.setText(RichTextUtils.getQueseAnswerStr(childAnswer, !isNeedTr&&isIndentChildAnswer, false));
        }

        TextView textView = findViewById(R.id.tv_child_answer_count);
        Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                    String childAnswerRichTxt = Html.fromHtml(childAnswer).toString();
                    int count = 0;
                    if (!TextUtils.isEmpty(childAnswerRichTxt)) {
                        String[] split = childAnswerRichTxt.replace("\n", " ").split(" ");
                        count = split.length;
                        for (String str : split) {
                            if (str.isEmpty()) {
                                count--;
                            }
                        }
                    }
                    emitter.onNext(Math.max(count, 0));
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this, true))
                .subscribe(integer -> {
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
                    spannableStringBuilder.append("Word Count:");
                    SpannableString spannableString = new SpannableString("" + integer);
                    spannableString.setSpan(new ForegroundColorSpan(0xff666666), 0, spannableString.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(spannableString);
                    textView.setText(spannableStringBuilder);
                }, throwable -> {

                });

        if (child.getItemList() == null || child.getItemList().size() == 0) {
            return;
        }
        if (TextUtils.equals(genreID, "34")) {//读后续写
            showContinueAnswer();
            return;
        }
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if (taskControlBean == null) {
            return;
        }
        String stuAnswer = item.getStuAnswer();
        String audioPath = item.getAudioPath();
        String videoPath = item.getVideoPath();
        List<String> imagePath = item.getImagePathList();
        String scanImagePath = item.getScanImagePath();
        if (!TextUtils.isEmpty(scanImagePath)) {
            ImageView img_scanner = findViewById(R.id.img_scanner);
            img_scanner.setVisibility(VISIBLE);
            Glide.with(img_scanner.getContext())
                    .load(item.getScanImagePath())
                    .into(img_scanner);
            findViewById(R.id.tv_ev_des).setVisibility(GONE);
            return;
        }
        if (TextUtils.isEmpty(stuAnswer) &&
                TextUtils.isEmpty(audioPath) &&
                (imagePath == null || imagePath.size() == 0 || TextUtils.isEmpty(imagePath.get(0))) &&
                TextUtils.isEmpty(videoPath)&&TextUtils.isEmpty(item.getImgRecognitionTxt())) {
            TextView tv_myAnswer = findViewById(R.id.tv_my_answer);
            tv_myAnswer.setText(R.string.ev_no_answer);
            tv_myAnswer.setVisibility(VISIBLE);
            findViewById(R.id.tv_ev_des).setVisibility(GONE);
        } else {
            if(taskControlBean.getExpired()){
                if (item.getWrittingAnswerType() == AnswerConstant.ANSWER_TYPE_PICTURE) {
                    boolean isUnAnswer = true;
                    if (imagePath != null && imagePath.size() > 0 &&
                            !TextUtils.isEmpty(imagePath.get(0))) {
                        loadPictureAnswer(imagePath);
                        isUnAnswer = false;
                    }
                    if (!TextUtils.isEmpty(item.getImgRecognitionTxt()) && !TextUtils.isEmpty(item.getImgRecognitionTxt().trim())) {
                        loadTxtAnswer(item.getImgRecognitionTxt(), !isUnAnswer);
                        isUnAnswer = false;
                    }
                    if (isUnAnswer) {
                        TextView tv_myAnswer = findViewById(R.id.tv_my_answer);
                        tv_myAnswer.setText(R.string.ev_no_answer);
                        tv_myAnswer.setVisibility(VISIBLE);
                        findViewById(R.id.tv_ev_des).setVisibility(GONE);
                    }
                } else {
                    if (TextUtils.isEmpty(stuAnswer) &&
                            TextUtils.isEmpty(audioPath)) {
                        TextView tv_myAnswer = findViewById(R.id.tv_my_answer);
                        tv_myAnswer.setText(R.string.ev_no_answer);
                        tv_myAnswer.setVisibility(VISIBLE);
                        findViewById(R.id.tv_ev_des).setVisibility(GONE);
                    } else {
                        if (!TextUtils.isEmpty(audioPath)) {
                            loadAudioAnswer(audioPath);
                        }
                        if (!TextUtils.isEmpty(stuAnswer)) {
                            loadTxtAnswer(stuAnswer, false);
                        }
                    }
                }
                return;
            }

            if (imagePath != null && imagePath.size() > 0 &&
                    !TextUtils.isEmpty(imagePath.get(0))) {
                loadPictureAnswer(imagePath);
                if (taskControlBean.getTrainSence() == 0) {
                    //如果是练习场景，图片作答里边还有文字作答，直接干掉文字作答信息
                    item.setStuAnswer("");
                    stuAnswer = "";
                } else {
                    if(!TextUtils.isEmpty(item.getImgRecognitionTxt())){
                        stuAnswer=item.getImgRecognitionTxt();
                    }
                    loadTxtAnswer(stuAnswer, true);
                    findViewById(R.id.tv_ev_des).setVisibility(GONE);
                    return;
                }
            }

            if (!TextUtils.isEmpty(stuAnswer)) {
                loadTxtAnswer(stuAnswer, false);
            }
            String imgRecognitionTxt = item.getImgRecognitionTxt();
            if(!TextUtils.isEmpty(imgRecognitionTxt)&&!TextUtils.isEmpty(imgRecognitionTxt.trim())){
                loadTxtAnswer(imgRecognitionTxt, true);
            }

            if (!TextUtils.isEmpty(audioPath)) {
                loadAudioAnswer(audioPath);
            }
            if (!TextUtils.isEmpty(videoPath)) {
                loadVideoAnswer(videoPath, 1000 * (item.getVideoDuration() == null ? 0 : item.getVideoDuration()), item.getVideoThumbnail());
            }
        }
        updateScoreState();
        TextView tv_greate = findViewById(R.id.tv_greate_ans);
        String greate = "查看更多优秀作答";
        SpannableString spannableString_greate = new SpannableString(greate);
        spannableString_greate.setSpan(new UnderlineSpan(), 0, greate.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_greate.setText(spannableString_greate);
        tv_greate.setVisibility(child.getItemList().get(0).getRECNum() > 0 ? VISIBLE : GONE);
        tv_greate.setOnClickListener(v -> {
            GreateAnsEvent event = new GreateAnsEvent(queseID);
            EventBus.getDefault().post(event);
        });

        loadHPMode(this);
    }

    /**
     * 加载文本作答内容
     *
     * @param stuAnswer 文本作答内容
     */
    private void loadTxtAnswer(String stuAnswer, boolean isPictureAnswer) {
        Log.e("eee", "加载文本作答内容" + stuAnswer+","+isPictureAnswer);
        if (TextUtils.isEmpty(stuAnswer)) {
            return;
        }
        ViewStub viewStub;
        if (!isPictureAnswer) {
            viewStub = findViewById(R.id.viewstub_composition_answer_looking_txt);
        }else{
            viewStub = findViewById(R.id.viewstub_composition_answer_looking_picture);
        }
        if (viewStub != null) {
            viewStub.inflate();
        }
        EditText editText = findViewById(R.id.edittext);
        if(editText==null){
            return;
        }
        editText.setVisibility(VISIBLE);

        editText.setBackgroundResource(R.drawable.ev_shape_3_corners_half_f7_bg);
        editText.setEnabled(false);
        editText.setText(stuAnswer);
        editText.setMinHeight(0);
        editText.setMinLines(1);
        TextView tv_answerCount = findViewById(R.id.tv_answer_count);
        tv_answerCount.setVisibility(VISIBLE);
        editText.setVisibility(VISIBLE);

        Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                    int count = 0;
                    if (!TextUtils.isEmpty(stuAnswer)) {
                        String[] split = stuAnswer.replace("\n", " ").split(" ");
                        count = split.length;
                        for (String str : split) {
                            if (str.isEmpty()) {
                                count--;
                            }
                        }
                    }
                    emitter.onNext(Math.max(count, 0));
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this,true))
                .subscribe(integer -> {
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
                    spannableStringBuilder.append("Word Count:");
                    SpannableString spannableString = new SpannableString("" + integer);
                    spannableString.setSpan(new ForegroundColorSpan(0xff666666), 0, spannableString.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(spannableString);
                    tv_answerCount.setText(spannableStringBuilder);
                }, error -> {
                });
        int dp12 = DpUtils.dip2px(getContext(), 12);
        ViewGroup.LayoutParams layoutParams = tv_answerCount.getLayoutParams();
        if (layoutParams instanceof LinearLayout.LayoutParams) {
            LinearLayout.LayoutParams layout = (LinearLayout.LayoutParams) layoutParams;
            layout.setMarginStart(0);
            layout.setMarginEnd(0);
            layout.topMargin = dp12;
            tv_answerCount.setLayoutParams(layout);
        } else if (layoutParams instanceof LayoutParams) {
            LayoutParams layout = (LayoutParams) layoutParams;
            layout.setMarginStart(0);
            layout.setMarginEnd(0);
            layout.topMargin = dp12;
            tv_answerCount.setLayoutParams(layout);
        }
        ViewGroup.LayoutParams layoutParams1 = editText.getLayoutParams();
        if (layoutParams1 instanceof LinearLayout.LayoutParams) {
            LinearLayout.LayoutParams layout = (LinearLayout.LayoutParams) layoutParams1;
            layout.width = LayoutParams.MATCH_PARENT;
            layout.height = LayoutParams.WRAP_CONTENT;
            layout.bottomMargin = 0;
            layout.leftMargin = 0;
            layout.rightMargin = 0;
            editText.setLayoutParams(layout);
        } else if (layoutParams1 instanceof LayoutParams) {
            LayoutParams layout = (LayoutParams) layoutParams1;
            layout.width = LayoutParams.MATCH_PARENT;
            layout.height = LayoutParams.WRAP_CONTENT;
            layout.bottomMargin = 0;
            editText.setLayoutParams(layout);
        }
    }


    /**
     * 加载图片作答内容
     *
     * @param imagePathList 图片作答内容
     */
    private void loadPictureAnswer(final List<String> imagePathList) {
        ViewStub viewStub = findViewById(R.id.viewstub_composition_answer_looking_picture);
        if (viewStub != null) {
            viewStub.inflate();
        }
        RecyclerView mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        ImageAdapter mAdapter = new ImageAdapter(imagePathList, 1);
        mAdapter.setImageOperateCallBack(new ImageAdapter.ImageOperateCallBack() {

            @Override
            public void gotoImageLibChoice() {
            }

            @Override
            public void deletChoiceImage(int position) {
            }

            @Override
            public void lookChoiceImage(int position) {
                EasyPhotos.startPreviewPaths((FragmentActivity) getContext(), GlideEngine.getInstance(), imagePathList, true, position);
            }

        });
        mRecyclerView.setAdapter(mAdapter);
        int dp8 = DpUtils.dip2px(getContext(), 8);
        ViewGroup.LayoutParams layoutParams = mRecyclerView.getLayoutParams();
        if (layoutParams instanceof LayoutParams) {
            LayoutParams relate = (LayoutParams) layoutParams;
            relate.setMarginStart(-dp8);
            relate.setMarginEnd(0);
            relate.topMargin = dp8;
            mRecyclerView.setLayoutParams(relate);
        } else if (layoutParams instanceof LinearLayout.LayoutParams) {
            LinearLayout.LayoutParams layout = (LinearLayout.LayoutParams) layoutParams;
            layout.setMarginStart(-dp8);
            layout.setMarginEnd(0);
            layout.topMargin = dp8;
            mRecyclerView.setLayoutParams(layout);
        }

    }

    /**
     * 加载图片作答内容
     *
     * @param audioPath 音频作答内容
     */
    private void loadAudioAnswer(final String audioPath) {
        ViewStub viewStub = findViewById(R.id.viewstub_composition_answer_looking_audio);
        if (viewStub != null) {
            viewStub.inflate();
        }
        childAudioView = findViewById(R.id.child_audio_view);
        childAudioView.setAudioPath(audioPath);
        childAudioView.setAudioTxt(R.string.ev_my_audio);

    }


    /**
     * 加载图片作答内容
     *
     * @param videoPath 视频作答内容
     */
    private void loadVideoAnswer(final String videoPath, long duration, String thumb) {
        ViewStub viewStub = findViewById(R.id.viewstub_composition_answer_looking_video);
        if (viewStub != null) {
            viewStub.inflate();
        }
        VideoPlayView videoPlayView = findViewById(R.id.videoPlayView);
        videoPlayView.reFresh(videoPath, false, duration, thumb);
        videoPlayView.setiVideoClick(new VideoPlayView.IVideoClick() {
            @Override
            public void onVideoClick(String url, boolean isPlaying) {
                List<String> paths = new ArrayList<>();
                paths.add(url);
                postVideoEvent(paths);
            }

            @Override
            public void onVideoLongClick(String url) {

            }
        });

    }

    /**
     * 更新作答得分
     */
    public void updateScoreState() {
        if (child == null || child.getItemList() == null) {
            return;
        }
        showComment();
        TextView tv_myScore = findViewById(R.id.tv_my_score);
        TextView tv_scorDes = findViewById(R.id.tv_score_des);
        float evalScore = child.getItemList().get(0).getEvalScore();
        String s = DecimalFormatUtils.RoundToTheNearestDecimalPlace1(evalScore);
        tv_myScore.setText(String.format("%s分", s));
        int state = ChildRightOrWrongJudgeUtils.judgeChildAnswerState(child);
        Log.e(TAG, "setFillResult: " + state);
        switch (state) {
            case 0:
                tv_myScore.setTextColor(0xffff4d4d);
                tv_scorDes.setTextColor(0xffff4d4d);
                break;
            case 1:
                tv_myScore.setTextColor(0xff00c063);
                tv_scorDes.setTextColor(0xff00c063);
                break;
            case 2:
                tv_myScore.setText("--");
                tv_myScore.setTextColor(0xff0099ff);
                tv_scorDes.setTextColor(0xff0099ff);
                break;
        }
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean != null &&taskControlBean.getExpired()){
            tv_myScore.setVisibility(GONE);
            tv_scorDes.setVisibility(GONE);
            TextView tv_title=findViewById(R.id.tv_my_answer_des);
            LayoutParams layoutParams = (LayoutParams) tv_title.getLayoutParams();
            layoutParams.topMargin=0;
            tv_title.setLayoutParams(layoutParams);
        }
        if (taskControlBean == null || taskControlBean.getShowLookingScoreType() == 0) {
            return;
        }
        tv_scorDes.setText(R.string.ev_answer_score_rate);
        if (state != 2) {
            tv_myScore.setText(String.format("%s%%", (int) (child.getItemList().get(0).getScoreRate() * 100)));
        }

    }

    private void postVideoEvent(List<String> paths) {
        VideoEventBean bean = new VideoEventBean();
        bean.setVideoList(paths);
        bean.setOperateType(2);
        EventBus.getDefault().post(bean);
    }


    public void pause() {
        Log.e(TAG, "pause");
        if (childAudioView != null) {
            childAudioView.pause();
        }
        if (compositionAnswerResultSubView != null) {
            compositionAnswerResultSubView.pause();
        }
    }

    public void release() {
        if (childAudioView != null) {
            childAudioView.release();
        }
        if (compositionAnswerResultSubView != null) {
            compositionAnswerResultSubView.release();
        }
    }

    private boolean isAnsweredEmpty(Item item) {
        if (!TextUtils.isEmpty(item.getStuAnswer())) {
            return false;
        } else if (item.getImagePathList() != null && item.getImagePathList().size() > 0) {
            return false;
        } else if (!TextUtils.isEmpty(item.getVideoPath())) {
            return false;
        } else return TextUtils.isEmpty(item.getAudioPath());
    }


    private void loadHPMode(View view) {
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if (taskControlBean == null) {
            return;
        }
        if (taskControlBean.isHp()) {
            view.findViewById(R.id.tv_ev_des).setVisibility(VISIBLE);
            view.findViewById(R.id.tv_my_score).setVisibility(GONE);
            view.findViewById(R.id.tv_score_des).setVisibility(GONE);

            LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.BELOW, R.id.scoreLayout);
            view.findViewById(R.id.tv_my_answer_des).setLayoutParams(params);

            view.findViewById(R.id.ll_score).setVisibility(VISIBLE);
            TextView tv_total = findViewById(R.id.totalScoreTv);
            tv_score = findViewById(R.id.scoreTv);
            if (item.getMutEvaluateScore() == -1) {
                tv_score.setText("请评分...");
            } else {
                tv_score.setText(DecimalFormatUtils.RoundToTheNearestDecimalPlace1(item.getMutEvaluateScore()));
            }
            tv_total.setText(String.format("分 (总分%s分)", DecimalFormatUtils.RoundToTheNearestDecimalPlace(item.getTotalScore())));
            tv_score = view.findViewById(R.id.scoreTv);

            if (isAnsweredEmpty(item)) {
                view.findViewById(R.id.addBtn).setBackgroundResource(R.drawable.ev_shape_pc_right_test_gray);
                view.findViewById(R.id.reduceBtn).setBackgroundResource(R.drawable.ev_subject_card_shape_pc_left_test_gray);
                tv_score.setText("0");
            } else {
                view.findViewById(R.id.addBtn).setBackgroundResource(R.drawable.ev_shape_pc_right_test);
                view.findViewById(R.id.reduceBtn).setBackgroundResource(R.drawable.ev_subject_card_shape_pc_left_test);
                view.findViewById(R.id.scoreTv).setOnClickListener(v -> showPcDialog(item.getMutEvaluateScore(), item.getTotalScore()));
                view.findViewById(R.id.addBtn).setOnClickListener(v -> addScore());
                view.findViewById(R.id.reduceBtn).setOnClickListener(v -> reduceScore());
            }
        } else {
            view.findViewById(R.id.ll_score).setVisibility(GONE);
            view.findViewById(R.id.tv_ev_des).setVisibility(GONE);
        }

    }

    private void showPcDialog(float score, float total) {
        PcDialog pcDialog = new PcDialog(getContext());
        pcDialog.setOnPcEnsureListener(score1 -> {
            item.setMutEvaluateScore(score1);
            tv_score.setText(DecimalFormatUtils.RoundToTheNearestDecimalPlace1(score1));
        });
        pcDialog.show(score, total);
    }

    private void addScore() {
        if (item.getMutEvaluateScore() >= 0 &&
                checkScoreRange(item.getMutEvaluateScore() + 0.5f)) {
            return;
        }
        float score = item.getMutEvaluateScore();
        if (score == -1) {
            score = 0;
        }
        score += 0.5f;

        item.setMutEvaluateScore(score);
        tv_score.setText(DecimalFormatUtils.RoundToTheNearestDecimalPlace1(score));
    }

    private boolean checkScoreRange(float score) {
        if (score > item.getTotalScore()) {
            Toast.makeText(getContext(), "输入分值不能大于总分", Toast.LENGTH_SHORT).show();
            return true;
        }
        if (score < 0) {
            Toast.makeText(getContext(), "输入分值不能小于0", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    private void reduceScore() {
        if(item==null){
            return;
        }
        if (item.getMutEvaluateScore() >= 0
                && checkScoreRange(item.getMutEvaluateScore() - 0.5f)) {
            return;
        }

        float score = item.getMutEvaluateScore();
        if (score == -1) {
            score = 0;
        }
        score -= 0.5f;

        item.setMutEvaluateScore(score);
        tv_score.setText(DecimalFormatUtils.RoundToTheNearestDecimalPlace1(score));
    }

    private void showContinueAnswer() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view_continue);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        List<ItemAsk> itemAskList = item.getItemAskList();
        compositionAnswerResultSubView = new CompositionAnswerResultSubView(itemAskList);
        recyclerView.setAdapter(compositionAnswerResultSubView);
        recyclerView.setVisibility(VISIBLE);
    }

    /**
     * 展示评语
     */
    private void showComment() {
        Log.e("eee","展示评语");
        if(child.getItemList()==null){
            return;
        }
        Item item = child.getItemList().get(child.getSelectedItemIndex());
        String comment = item.getComment();
        Log.e("eee",item.getNoteFlag()+"展示评语:"+comment);
        if(item.getNoteFlag()==1){
            findViewById(R.id.tv_comments_look).setVisibility(VISIBLE);
            findViewById(R.id.tv_comments_look).setOnClickListener(this);
        }
        if(comment==null||TextUtils.isEmpty(comment)||TextUtils.isEmpty(comment.trim())){
            return;
        }
        findViewById(R.id.tv_comment_des).setVisibility(VISIBLE);
        findViewById(R.id.tv_comment).setVisibility(VISIBLE);

        findViewById(R.id.tv_comment).setOnClickListener(this);
        findViewById(R.id.tv_comment_des).setOnClickListener(this);
        TextView tv_comment = findViewById(R.id.tv_comment);

        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(comment.trim());
        SpannableString spannableString = new SpannableString("123");
        spannableString.setSpan(new CenteredImageSpan(tv_comment.getContext(), R.drawable.ev_vector_comment_details), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableStringBuilder.append(" ");
        spannableStringBuilder.append(spannableString);
        tv_comment.setText(spannableStringBuilder);
    }


    @Override
    public void onClick(View v) {
        if (System.currentTimeMillis() - clickTime < 500) {
            return;
        }
        clickTime = System.currentTimeMillis();
        int id = v.getId();
        if (id == R.id.tv_comments_look) {
            //查看批注
            Log.e(TAG, "onClick: " + "点击查看批注");
            List<Item> itemList = child.getItemList();
            if(itemList==null){
                return;
            }
            Item item =itemList.get(child.getSelectedItemIndex());
            CommentsNoteEventBean bean=new CommentsNoteEventBean();
            bean.setItemIndex(item.getItemIndex());
            bean.setStuAnswer(item.getWrittingAnswerType() == AnswerConstant.ANSWER_TYPE_PICTURE ? item.getImgRecognitionTxt() : item.getStuAnswer());
            EventBus.getDefault().post(bean);
        } else if (id == R.id.tv_comment_des || id == R.id.tv_comment) {
            List<Item> itemList = child.getItemList();
            if(itemList==null){
                return;
            }
            Item item = itemList.get(child.getSelectedItemIndex());
            DetailComment detailComment = item.getDetailComment();
            if(detailComment==null){
                CommentDetailEventBean bean=new CommentDetailEventBean();
                bean.setAnswerPointIndex(item.getAnswerPointIndex());
                bean.setQuesID(ques.getQuesID());
                bean.setItemIndex(item.getItemIndex());
                bean.setQuesIndex(0);
                bean.setChildIndex(0);
                EventBus.getDefault().post(bean);
                return;
            }
            String comment = item.getComment();
            float evalScore = item.getEvalScore();
            float totalScore = item.getTotalScore();
            CompositionComment bean=new CompositionComment(comment==null?"":comment,evalScore,totalScore,detailComment);
            //查看评语详情
            CompositionCommentActivity.Companion.launch(getContext(), bean, 1, 0);
        }
    }


    public void adjustFontSize(){
        TextView textView = findViewById(R.id.tv_score_des);
        TextView textView1 = findViewById(R.id.tv_my_score);
        TextView textView2 = findViewById(R.id.tv_my_answer_des);
        TextView textView3 = findViewById(R.id.tv_comments_look);
        TextView textView4 = findViewById(R.id.tv_my_answer);
        TextView textView7 = findViewById(R.id.tv_comment_des);
        TextView textView8 = findViewById(R.id.tv_comment);
        TextView textView9 = findViewById(R.id.tv_answer_des);
        TextView textView10 = findViewById(R.id.tv_greate_ans);
        TextView textView11 = findViewById(R.id.tv_child_answer_count);
        TextView textView12 = findViewById(R.id.tv_answer);
        AnswerAnalysisView answerAnalysisView = findViewById(R.id.answer_analysis_view);
        answerAnalysisView.adjustFontSize();
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView12,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView11,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView10,14);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView9,14);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView8,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView7,14);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView4,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView3,14);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView2,14);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView1,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView,13);

        ChildAudioView childAudioView=findViewById(R.id.child_audio_view);
        if(childAudioView!=null){
            childAudioView.adjustFontSize();
        }
        PictureAnswerView pictureAnswerView=findViewById(R.id.pav);
        if(pictureAnswerView!=null){
            pictureAnswerView.adjustFontSize();
        }

        TextView textView5 = findViewById(R.id.tv_answer_count);
        TextView textView6 = findViewById(R.id.edittext);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView5,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView6,13);



    }
}
